import UIKit
import  GrowingTextView
import SwiftEventBus

class CreateRoleViewController: UIViewController{

    var promptTextView: GrowingTextView!
    var pageTitle = "创建角色"
    var containerView: UIView!
    let scrollView = UIScrollView()
    let titleTextField = UITextField()
    let descriptionTextField = UITextField()
    var clearButton: UIButton!
    override func viewDidLoad() {
        navigationItem.title = pageTitle
        view.backgroundColor = primaryDarkBackgroundColor
        
        view.addSubview(scrollView)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-56)
        }
        containerView = UIView()
        scrollView.addSubview(containerView)
        containerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(UIScreen.main.bounds.width)
        }
        
        
        let titleLabel = UILabel()
        titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
        titleLabel.textColor = .white
    
        titleLabel.text = "名称"
        containerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints({ make in
            make.top.equalTo(containerView.safeAreaLayoutGuide.snp.top).offset(12)
            make.left.equalTo(containerView).offset(16)
        })
        
        
        containerView.addSubview(titleTextField)
        titleTextField.textColor = .white
        titleTextField.borderStyle = .roundedRect
        titleTextField.attributedPlaceholder  = NSAttributedString(
            string: "请输入角色名称",
            attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
        )
        titleTextField.backgroundColor = primaryBackgroundColor
        titleTextField.clearButtonMode = .whileEditing
        
        titleTextField.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.height.equalTo(42)
            make.left.equalTo(containerView).offset(16)
            make.width.equalTo(UIScreen.main.bounds.width-32)
            
        }
        
        
        let descriptionLabel = UILabel()
        descriptionLabel.font = UIFont.boldSystemFont(ofSize: 15)
        descriptionLabel.textColor = .white
    
        descriptionLabel.text = "描述"
        containerView.addSubview(descriptionLabel)
        descriptionLabel.snp.makeConstraints({ make in
            make.top.equalTo(titleTextField.snp.bottom).offset(12)
            make.left.equalTo(containerView).offset(16)
        })
        
        
        containerView.addSubview(descriptionTextField)
        descriptionTextField.textColor = .white
        descriptionTextField.attributedPlaceholder  = NSAttributedString(
            string: "请输入角色描述",
            attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
        )
        descriptionTextField.backgroundColor = primaryBackgroundColor
        descriptionTextField.borderStyle = .roundedRect
        descriptionTextField.textAlignment = .left
        descriptionTextField.clearButtonMode = .whileEditing
        
        descriptionTextField.snp.makeConstraints { make in
            make.top.equalTo(descriptionLabel.snp.bottom).offset(12)
            make.height.equalTo(72)
            make.left.equalTo(containerView).offset(16)
            make.width.equalTo(UIScreen.main.bounds.width-32)
        }
        
        
        
        let promptLabel = UILabel()
        promptLabel.font = UIFont.boldSystemFont(ofSize: 15)
        promptLabel.textColor = .white
        promptLabel.text = "角色指令"
        containerView.addSubview(promptLabel)
        promptLabel.snp.makeConstraints({ make in
            make.top.equalTo(descriptionTextField.snp.bottom).offset(24)
            make.left.equalTo(containerView).offset(16)
        })
        
        
        let promptButton = UIButton(type: .custom)
        promptButton.setTitle("不知道如何写指令？", for: .normal)
        promptButton.setTitleColor(.primaryColor, for: .normal)
        promptButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        
        promptButton.isUserInteractionEnabled = true
        promptButton.addTarget(self, action: #selector(handlePromptButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(promptButton)
        promptButton.snp.makeConstraints({ make in
            make.top.equalTo(descriptionTextField.snp.bottom).offset(24)
            make.right.equalTo(containerView).offset(-16)
        })
        
        promptTextView = GrowingTextView()
        promptTextView.minHeight = UIScreen.main.bounds.height/5
        promptTextView.maxHeight = UIScreen.main.bounds.height/4
        promptTextView.tintColor = .white
        promptTextView.backgroundColor = primaryBackgroundColor
        promptTextView.placeholder = "请填写角色指令，越详细越好。"
        promptTextView.layer.cornerRadius = 12
        promptTextView.font = UIFont.systemFont(ofSize: 15)
        containerView.addSubview(promptTextView)
        promptTextView.snp.makeConstraints({ make in
            make.top.equalTo(promptLabel.snp.bottom).offset(12)
            make.left.equalTo(containerView).offset(16)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(UIScreen.main.bounds.width-32)
        })
        
        
        clearButton = UIButton(type: .custom)
        clearButton.setTitle((promptTextView.text == nil || promptTextView.text == "") ? "粘贴" :  "清空", for: .normal)
        clearButton.setTitleColor(.primaryColor, for: .normal)
        clearButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        
        clearButton.isUserInteractionEnabled = true
        clearButton.addTarget(self, action: #selector(handleClearButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(clearButton)
        clearButton.snp.makeConstraints({ make in
            make.bottom.equalTo(promptTextView.snp.bottom)
            make.right.equalTo(promptTextView)
            make.width.equalTo(62)
            make.height.equalTo(32)
        })
        
       
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.6){
//            self.titleTextField.becomeFirstResponder()
//        }
        
        containerView.snp.makeConstraints({ (make) in
            make.bottom.equalTo(promptTextView.snp.bottom)
            
        })
        
        self.view.isUserInteractionEnabled = true
        self.view.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(self.handleTap(_:))))
        
        
        let completionButton = UIButton(type: .custom)
        completionButton.setTitle("开始创建", for: .normal)
        completionButton.setTitleColor(.white, for: .normal)
        completionButton.layer.cornerRadius = 21
        completionButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        completionButton.frame.size = CGSize(width: 68, height: 20)
        completionButton.backgroundColor = .primaryColor
        completionButton.addTarget(self, action: #selector(handleCompletionButtonTapped(_:)), for: .touchUpInside)
        self.view.addSubview(completionButton)
        completionButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-42)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width*2/3)
            
        }
        
        let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0,  width: self.view.frame.size.width, height: 30))
                let flexSpace = UIBarButtonItem(barButtonSystemItem:    .flexibleSpace, target: nil, action: nil)
                let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(dismissMyKeyboard))
                toolbar.setItems([flexSpace, doneBtn], animated: false)
                toolbar.sizeToFit()
        promptTextView.inputAccessoryView = toolbar
        descriptionTextField.inputAccessoryView = toolbar
        titleTextField.inputAccessoryView = toolbar
        
        
        SwiftEventBus.onMainThread(self, name: EVENT_NAME_SELECT_ROLE) { result in
            if let result = result{
                let prompt : Prompt = result.object as! Prompt
                
                self.titleTextField.text = prompt.title
                self.promptTextView.text = prompt.description
            }
            
        }
       
    }
    
    @objc func dismissMyKeyboard() {
           view.endEditing(true)
       }
    
    @objc private func handleCompletionButtonTapped(_ sender: Any) {
        if let title = titleTextField.text, let description = descriptionTextField.text,let prompt = promptTextView.text{
            if title != "" && description != "" && prompt != ""{
                let role = Role(id: 0,title:title, description: description,prompt: prompt,custom: true)
                SwiftEventBus.post(EVENT_NAME_ADD_ROLE, sender: role)
                self.view.makeToast("创建成功",position: .center)
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.6){
                    self.navigationController?.popViewController(animated: true)
                }
            }else{
                self.view.makeToast("标题表述指令不能为空",position: .center)
            }
        }
        
    }
    @objc private func handleTap(_ sender: Any) {
        self.view.endEditing(true)
        print("handleTap")
        
    }
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
    
    @objc private func handlePromptButtonTapped(_ sender: Any) {
        print("不知道如何写指令")
        self.navigationController?.pushViewController(PromptViewController(), animated: true)
    }
    
    @objc private func handleClearButtonTapped(_ sender: Any) {
        if let text = promptTextView.text {
            if text == "" {
                let pasteboard = UIPasteboard.general
                if let pasteboardString = pasteboard.string {
                    promptTextView.text = pasteboardString
                    print("粘贴板的内容是：\(pasteboardString)")
                } else {
                    self.view.makeToast("粘贴板没有可用的字符串内容",position: .center)
                   
                    print("粘贴板没有可用的字符串内容")
                }
            }else{
                promptTextView.text = ""
            }
            clearButton.setTitle((promptTextView.text == nil || promptTextView.text == "") ? "粘贴" :  "清空", for: .normal)
        }
        
    }
}
